import json
import time
import requests

token = "j-d8xBkdm2F6WVoJYAZLpZZPGDNL2UbycLC58H7u6m8"  ## 您在用户中心获取的


def create_task(googlekey, pageurl, data_s="", invisible=0):
    _headers = {
        'Content-Type': 'application/json'
    }
    """
    第一步，创建验证码任务
    :param
    :return taskId : string 创建成功的任务ID
    """
    url = "http://api.jfbym.com/api/YmServer/funnelApi"
    payload = json.dumps({
        "token": token,
        "type": 40003,  ## v2
        # "type": "40004", ## v3
        "googlekey": googlekey,
        "enterprise": 1,  ## 是否为企业版
        "pageurl": pageurl,
        "invisible": invisible,
        "data-s": data_s,  ## V2+企业如果能找到，找不到传空字符串
        # 'action':"" #V3必传
        # 'min_score':"" #V3才支持的可选参数
    })

    try:
        # 发送JSON格式的数据
        print(payload)
        result = requests.request("POST", url, headers=_headers, data=payload).json()
        print(result)
        # {'msg': '识别成功', 'code': 10000, 'data': {'code': 0, 'captchaId': '51436618130', 'recordId': '74892'}}
        captcha_id = result.get('data').get("captchaId")
        record_id = result.get('data').get("recordId")
        if captcha_id and record_id:
            return captcha_id, record_id

    except Exception as e:
        print(e)


def get_response(captcha_id, record_id):
    """
    第二步：使用taskId获取response
    :param recordId:
    :param captchaId:
    :param taskID: string
    :return response: string 识别结果
    """
    # 循环请求识别结果，5秒请求一次
    _headers = {
        'Content-Type': 'application/json'
    }
    times = 0
    is_solved = 0
    while times < 150:
        try:
            url = f"http://api.jfbym.com/api/YmServer/funnelApiResult"
            data = {
                "token": token,
                "captchaId": captcha_id,
                "recordId": record_id
            }
            result = requests.post(url, headers=_headers, json=data).json()
            print(result)
            if result['msg'] == "结果准备中，请稍后再试":
                continue
            if result['msg'] == '请求成功' and result['code'] == 10001:
                is_solved = 1
                return result['data']['data']
        except Exception as e:
            print(e)
        finally:
            if is_solved:
                return result['data']['data']
            if result['msg'] == "请求已结束":
                break
            # print("sleep 5s...")
            time.sleep(5)
            times += 5

def recaptcha_run(site_key, site_url):
    data_s = ""
    captcha_id, record_id = create_task(googlekey=site_key, pageurl=site_url, data_s=data_s)
    r = get_response(captcha_id, record_id)
    return r

# site_key = "6Lejfp8pAAAAAJrnJ4-oIeKBkb0KmGt_5VKgEGO_"
# site_url = "https://online.seranking.com/login.html?back=true&do=login"
# recaptcha_run(site_key, site_url)